<?php
namespace Model;

use Model\Factory\TableGatewayFactory;

class Privilege extends AbstractModel
{
    public $id;
    public $code;
    public $description;
    public $name;
    public $type_id;
    public $created_date;
    public $created_by;
    public $active;


    public function updateRole($roleId, $checked)
    {
        $rolePrivilegeTable = TableGatewayFactory::getRolePrivilegeTable();

        if($checked){
            $select = $rolePrivilegeTable->getDbSqlSelect();
            $select->where(array('role_id'=>$roleId, 'privilege_id'=>$this->id));
            $allCouple = $rolePrivilegeTable->getTableGateway()->selectWith($select);
            if($allCouple->count() > 0) return;
            $rolePrivilegeTable->insert(array("role_id"=>$roleId, "privilege_id"=>$this->id));
        }else{
            $rolePrivilegeTable->getTableGateway()->delete(
                array('role_id'=>$roleId, 'privilege_id'=>$this->id));
        }
    }

    public function detachAllRole(){
        $rolePrivilegeTable = TableGatewayFactory::getRolePrivilegeTable();
        $rolePrivilegeTable->getTableGateway()->delete(
            array( 'privilege_id'=>$this->id));
    }

    public function  getBelongedRole(){
        $rolePrivilegeTable = TableGatewayFactory::getRoleTable();
        return $rolePrivilegeTable->getRolesContainPrivilege($this->id);
    }


}
